<template>
  <section class="winner-manage">
    <div class="winner-classify">
      <div class="winner-classify-inner">
        <div class="inner-item">
          <ul>
            <li>奖项分类:</li>
            <li :class="{ 'active': listQuery.winningId === '' }" @click="classifyClick('')">全部</li>
            <li
              v-for="item in classifyOptions"
              :key="item.id"
              :class="{ 'active': listQuery.winningId == item.id }"
              @click="classifyClick(item.id)"
            >{{ item.winningName }}
            </li>
          </ul>
        </div>
      </div>
      <div class="winner-classify-btn">
        <el-button
          style="padding: 10px 16px;"
          class="filter-item"
          type="primary"
          @click="handleClassify"
        >奖项管理
        </el-button>
      </div>
    </div>
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>获奖管理</span>
      </section>
      <section class="main-buttons-btns" />
      <el-button style="margin-left: 10px" @click="handleDownload">下载批量导入模版</el-button>
      <el-button style="margin-left: 10px" @click="handleUpload">导入奖项清单</el-button>
      <el-button style="margin-left: 10px" @click="handleExport">导出奖项清单</el-button>
      <el-button style="margin-left: 10px" @click="handlePublishs">批量发布</el-button>
      <el-button style="margin-left: 10px" @click="handleCreate">新增获奖作品</el-button>
      <el-button style="margin-left: 10px" @click="back">返回</el-button>
    </section>
    <section class="main-table">
      <v-table
        :list="list"
        tag="winnerWorks"
        :source-arr="['worksCover']"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
        :selection="false"
      >
        <el-table-column label="操作" fixed="right" align="center" min-width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <template v-if="listQuery.winningId">
              <el-button type="text" size="mini" @click="handlePublish(scope.row)">
                {{ scope.row.awardWinningWorksStatus === 'GIPSTSTUS01' ? '取消发布' : '发布' }}
              </el-button>
              <el-button type="text" size="mini" @click="handleSort(scope.row)">排序</el-button>
              <el-button type="text" size="mini" @click="deleteWorks(scope.row.awardWinningWorksId)">删除</el-button>
            </template>
            <el-button type="text" size="mini" @click="handleView(scope.row)">查看作品</el-button>
          </template>
        </el-table-column>
      </v-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <el-dialog
        el-drag-dialog
        :close-on-click-modal="false"
        :visible.sync="classifyDialogVisible"
        title="奖项管理"
        center
        width="700px"
      >
        <classify :parentref="true" @onrefresh="onrefreshClassify" />
        <div slot="footer" class="dialog-footer">
          <el-button style="padding: 8px 30px;" @click="classifyDialogVisible = false">关 闭</el-button>
        </div>
      </el-dialog>
      <works v-if="selectWorks" :solicitation-id="activityId" @cancel="selectWorks = false" @comit="confirmWorks" />
      <!--导入      -->
      <v-upload v-if="showupload" :id="activityId" @success="handleUploadSuccess" @cancel="handleUploadCancel" />
      <works-preview v-if="worksPreviewStatus" :id="worksId" @closeSet="worksPreviewStatus = false" />
    </section>
  </section>
</template>
<script>
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import { queryAwards, queryPage, del, updateState, insert, updateSort, maskAPI, noMaskAPI } from '../api/winner'
import permission from '@/directive/permission/index.js'
import Classify from '../components/Classify'
import Works from '../components/Works'
import elDragDialog from '@/directive/el-drag-dialog'
import VUpload from '@/views/activity/zjhd/components/upload'
import CryptoJS from '@/utils/aesJiaJM'
import WorksPreview from '../components/WorksPreview'
import { exportSign } from '@/utils/fileImportOrExportSign'
import { exportCheck } from '@/utils/sensitiveInfoExportCheck'
export default {
  name: 'WinnerManage',
  components: { Pagination, VTable, Classify, Works, VUpload, WorksPreview },
  directives: { permission, elDragDialog },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 10,
        winningId: ''
      },
      classifyOptions: [],
      list: [],
      total: 0,
      listLoading: false,
      setType: 'single',
      classifyDialogVisible: false,
      selectWorks: false,
      showupload: false,
      view: '/API-DOCUMENT/document/file/download?id=',
      activityId: '',
      worksId: '',
      worksPreviewStatus: false
    }
  },
  created() {
    if (this.$route.query.ai) {
      this.activityId = this.$route.query.ai
      this.getClassifyOption()
    } else {
      this.$message.error('参数错误')
      this.$router.back()
    }
  },
  methods: {
    /**
     * 批量发布
     */
    handlePublishs() {
      this.$confirm('确认发布？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateState({ solicitationId: this.$route.query.ai, status: 'GIPSTSTUS01' }).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {

      })
    },
    /**
     * 发布/取消发布
     */
    handlePublish(row) {
      this.$confirm(row.awardWinningWorksStatus === 'GIPSTSTUS01' ? '确认取消发布？' : '确认发布？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateState({
          solicitationId: this.$route.query.ai,
          id: row.awardWinningWorksId,
          status: row.awardWinningWorksStatus === 'GIPSTSTUS01' ? 'GIPSTSTUS02' : 'GIPSTSTUS01'
        }).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {

      })
    },
    /**
     * 导出
     * */
    handleExport() {
      const query = {
        solicitationId: this.activityId
      }
      if (this.listQuery.winningId) {
        const winningName = this.classifyOptions.find(item => { return item.id === this.listQuery.winningId }).winningName
        this.$confirm(`您当前选择的奖项为：${winningName}，是否导出所有奖项的获奖作品？`, '提示', {
          confirmButtonText: '导出所有奖项',
          cancelButtonText: `只导出${winningName}`,
          distinguishCancelAndClose: true
        }).then(() => {
          query['winningId'] = ''
          this.confirmExport(query)
        }).catch((action) => {
          if (action === 'cancel') {
            query['winningId'] = this.listQuery.winningId
            this.confirmExport(query)
          }
        })
      } else {
        query['winningId'] = ''
        this.confirmExport(query)
      }
    },
    confirmExport(query) {
      // const loading = this.$loading({
      //   lock: true,
      //   text: '请稍后',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.3)'
      // })
      const obj = exportSign(query).obj
      exportCheck('STAFF_SERVICE_SOLICITATION', this.$route.query.ai, maskAPI, noMaskAPI, obj, '奖项清单.xlsx')
      // exportFile(obj).then((res) => {
      //   loading.close()
      //   const content = res.data
      //   const blob = new Blob([content])
      //   const fileName = '奖项清单.xlsx'
      //   if ('download' in document.createElement('a')) {
      //     const elink = document.createElement('a')
      //     elink.download = fileName
      //     elink.style.display = 'none'
      //     elink.href = URL.createObjectURL(blob)
      //     document.body.appendChild(elink)
      //     elink.click()
      //     URL.revokeObjectURL(elink.href) // 释放URL 对象
      //     document.body.removeChild(elink)
      //   } else {
      //     navigator.msSaveBlob(blob, fileName)
      //   }
      // }).catch(() => {
      //   // this.$message.error()
      //   loading.close()
      // })
    },
    handleUpload() {
      this.showupload = true
    },
    handleUploadSuccess() {
      this.getList()
    },
    handleUploadCancel() {
      this.showupload = false
    },
    /**
     * 下载模板
     * */
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/awardWinningWorks/downloadAwardWinningWorksTemplate' + exportSign({}).paramStr
      link.setAttribute('download', '奖项清单模版.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    /**
     * 确认选择作品
     */
    confirmWorks(arr) {
      const worksIds = arr.map(item => {
        return item.id
      }).join(',')
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        insert({
          solicitationId: this.$route.query.ai,
          worksShowId: worksIds,
          winningId: this.listQuery.winningId
        }).then(({ data }) => {
          this.selectWorks = false
          loading.close()
          this.$message({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 分类管理
     */
    handleClassify() {
      this.classifyDialogVisible = true
    },

    classifyClick(id) {
      this.listQuery.winningId = id
      this.getList()
    },

    /**
     * 获取分类
     */
    getClassifyOption() {
      return new Promise((resolve, reject) => {
        queryAwards({ dataId: this.$route.query.ai, dataType: 'ZJHD' }).then(({ data }) => {
          this.classifyOptions = data.data || []
          if (data.data.length > 0) {
            this.listQuery.winningId = this.$route.query.t || ''
            this.getList()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 更新分类
     */
    onrefreshClassify(data) {
      this.classifyOptions = JSON.parse(JSON.stringify(data))
      if (this.listQuery.winningId !== '') {
        const result = this.classifyOptions.find(item => {
          return item.id === this.listQuery.winningId
        })
        if (result === undefined || result === 'undefined') {
          this.listQuery.winningId = ''
          this.getList()
        }
      }
    },
    /**
     * 新建
     */
    handleCreate() {
      if (this.classifyOptions.length == 0) {
        this.$message({
          type: 'warning',
          message: '请先添加奖项分类'
        })
        return
      }
      if (this.listQuery.winningId === '') {
        this.$message({
          type: 'warning',
          message: '请先选择奖项分类'
        })
        return
      }
      this.selectWorks = true
    },
    back() {
      this.$router.back()
    },
    handleSort(row) {
      this.$prompt('请输入排序号（越小越靠前）', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'Number',
        inputValue: row.sort || '',
        closeOnClickModal: false,
        inputValidator: (val) => {
          const reg = /^\+?[1-9][0-9]*$/
          if (reg.test(val)) {
            return true
          } else {
            return '请填写非零正整数'
          }
        }
      }).then(({ value }) => {
        return new Promise((resolve, reject) => {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          updateSort({ sort: value, id: row.awardWinningWorksId }).then((res) => {
            loading.close()
            this.$message({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      })
    },
    /**
     * 预览
     */
    handleView(row) {
      this.worksId = row.id
      this.worksPreviewStatus = true
    },
    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.getList()
    },
    deleteWorks(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          del({ id: ids }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {
        /* this.$message({
           type: 'info',
           message: '已取消删除'
         })*/
      })
    },

    filtercolumn(scope, item) {
      if (item === 'worksCover') {
        return this.view + scope.row[item]
      } else if (item === 'authorPhoneNumber' || item === 'authorIdNumber') {
        return scope.row[item] ? CryptoJS.$aesJieM(scope.row[item]) : '--'
      } else {
        return scope.row[item]
      }
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        solicitationId: this.$route.query.ai,
        winningId: this.listQuery.winningId
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss">

.winner-manage {
  padding: 10px;

  .winner-classify {
    display: flex;
    background-color: #fff;
    margin-top: 10px;
    margin-bottom: 10px;

    .winner-classify-inner {
      flex: 1;

      .inner-item {
        position: relative;

        ul {
          padding: 5px 20px;
          margin: 0;
          box-shadow: 0 5px 10px rgba(254, 90, 97, 0.05);
          max-height: 50px;
          transition: all 1s ease;
          overflow: hidden;

          li {
            list-style-type: none;
            display: inline-block;
            padding: 6px 12px;
            font-size: 14px;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(51, 51, 51, 1);
            margin: 5px;
            cursor: pointer;

            &:first-child {
              color: #a6a6a6;
            }

            &.active {
              @include font-color($mainColor);
              background: rgba(228, 77, 66, 0.1);
              border-radius: 17px;
            }
          }

          &.toggle {
            max-height: 300px;
          }
        }

        span {
          position: absolute;
          right: 10px;
          top: 12px;
          @include font-color($mainColor);
          cursor: pointer;
          font-size: 20px;
        }
      }
    }

    .winner-classify-btn {
      position: relative;
      width: 120px;

      .el-button {
        position: absolute;
        top: 50%;
        margin-top: -18px;
        left: 50%;
        margin-left: -45px;
      }
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>
